2
0

[[...path]].page.tsx 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  1. import type { ReactNode } from 'react';
  2. import React, { useEffect } from 'react';
  3. import EventEmitter from 'events';
  4. import { isIPageInfo } from '@growi/core';
  5. import type {
  6. IDataWithMeta, IPageInfo, IPagePopulatedToShowRevision,
  7. } from '@growi/core';
  8. import {
  9. isClient, pagePathUtils, pathUtils,
  10. } from '@growi/core/dist/utils';
  11. import ExtensibleCustomError from 'extensible-custom-error';
  12. import type {
  13. GetServerSideProps, GetServerSidePropsContext,
  14. } from 'next';
  15. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  16. import dynamic from 'next/dynamic';
  17. import Head from 'next/head';
  18. import { useRouter } from 'next/router';
  19. import superjson from 'superjson';
  20. import { BasicLayout } from '~/components/Layout/BasicLayout';
  21. import { PageView } from '~/components/PageView/PageView';
  22. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript';
  23. import { SupportedAction, type SupportedActionType } from '~/interfaces/activity';
  24. import type { CrowiRequest } from '~/interfaces/crowi-request';
  25. import { RegistrationMode } from '~/interfaces/registration-mode';
  26. import type { RendererConfig } from '~/interfaces/services/renderer';
  27. import type { ISidebarConfig } from '~/interfaces/sidebar-config';
  28. import type { CurrentPageYjsData } from '~/interfaces/yjs';
  29. import type { PageModel, PageDocument } from '~/server/models/page';
  30. import type { PageRedirectModel } from '~/server/models/page-redirect';
  31. import { useEditorModeClassName } from '~/services/layout/use-editor-mode-class-name';
  32. import {
  33. useCurrentUser,
  34. useIsForbidden, useIsSharedUser,
  35. useIsEnabledStaleNotification, useIsIdenticalPath,
  36. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  37. useDefaultIndentSize, useIsIndentSizeForced,
  38. useIsAclEnabled, useIsSearchPage, useIsEnabledAttachTitleHeader,
  39. useCsrfToken, useIsSearchScopeChildrenAsDefault, useIsEnabledMarp, useCurrentPathname,
  40. useIsSlackConfigured, useRendererConfig, useGrowiCloudUri,
  41. useIsAllReplyShown, useIsContainerFluid, useIsNotCreatable,
  42. useIsUploadAllFileAllowed, useIsUploadEnabled,
  43. useElasticsearchMaxBodyLengthToIndex,
  44. useIsLocalAccountRegistrationEnabled,
  45. } from '~/stores-universal/context';
  46. import { useEditingMarkdown } from '~/stores/editor';
  47. import {
  48. useSWRxCurrentPage, useSWRMUTxCurrentPage, useCurrentPageId,
  49. useIsNotFound, useIsLatestRevision, useTemplateTagData, useTemplateBodyData,
  50. } from '~/stores/page';
  51. import { useRedirectFrom } from '~/stores/page-redirect';
  52. import { useRemoteRevisionId } from '~/stores/remote-latest-page';
  53. import { useSetupGlobalSocket, useSetupGlobalSocketForPage } from '~/stores/websocket';
  54. import { useCurrentPageYjsData, useSWRMUTxCurrentPageYjsData } from '~/stores/yjs';
  55. import loggerFactory from '~/utils/logger';
  56. import type { NextPageWithLayout } from './_app.page';
  57. import type { CommonProps } from './utils/commons';
  58. import {
  59. getNextI18NextConfig, getServerSideCommonProps, generateCustomTitleForPage, useInitSidebarConfig, skipSSR, addActivity,
  60. } from './utils/commons';
  61. declare global {
  62. // eslint-disable-next-line vars-on-top, no-var
  63. var globalEmitter: EventEmitter;
  64. }
  65. const GrowiContextualSubNavigationSubstance = dynamic(() => import('~/client/components/Navbar/GrowiContextualSubNavigation'), { ssr: false });
  66. const GrowiPluginsActivator = dynamic(() => import('~/features/growi-plugin/client/components').then(mod => mod.GrowiPluginsActivator), { ssr: false });
  67. const DisplaySwitcher = dynamic(() => import('~/client/components/Page/DisplaySwitcher').then(mod => mod.DisplaySwitcher), { ssr: false });
  68. const PageStatusAlert = dynamic(() => import('~/client/components/PageStatusAlert').then(mod => mod.PageStatusAlert), { ssr: false });
  69. const UnsavedAlertDialog = dynamic(() => import('~/client/components/UnsavedAlertDialog'), { ssr: false });
  70. const DescendantsPageListModal = dynamic(
  71. () => import('~/client/components/DescendantsPageListModal').then(mod => mod.DescendantsPageListModal),
  72. { ssr: false },
  73. );
  74. const DrawioModal = dynamic(() => import('~/client/components/PageEditor/DrawioModal').then(mod => mod.DrawioModal), { ssr: false });
  75. const HandsontableModal = dynamic(() => import('~/client/components/PageEditor/HandsontableModal').then(mod => mod.HandsontableModal), { ssr: false });
  76. const TemplateModal = dynamic(() => import('~/client/components/TemplateModal').then(mod => mod.TemplateModal), { ssr: false });
  77. const LinkEditModal = dynamic(() => import('~/client/components/PageEditor/LinkEditModal').then(mod => mod.LinkEditModal), { ssr: false });
  78. const TagEditModal = dynamic(() => import('~/client/components/PageTags/TagEditModal').then(mod => mod.TagEditModal), { ssr: false });
  79. const ConflictDiffModal = dynamic(() => import('~/client/components/PageEditor/ConflictDiffModal').then(mod => mod.ConflictDiffModal), { ssr: false });
  80. const QuestionnaireModalManager = dynamic(() => import('~/features/questionnaire/client/components/QuestionnaireModalManager'), { ssr: false });
  81. const EditablePageEffects = dynamic(() => import('~/client/components/Page/EditablePageEffects').then(mod => mod.EditablePageEffects), { ssr: false });
  82. const logger = loggerFactory('growi:pages:all');
  83. const {
  84. isPermalink: _isPermalink, isCreatablePage,
  85. } = pagePathUtils;
  86. const { removeHeadingSlash } = pathUtils;
  87. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfo>;
  88. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  89. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  90. {
  91. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  92. return v?.data != null
  93. && v?.data.toObject != null
  94. && isIPageInfo(v.meta);
  95. },
  96. serialize: (v) => {
  97. return {
  98. data: superjson.stringify(v.data.toObject()),
  99. meta: superjson.stringify(v.meta),
  100. };
  101. },
  102. deserialize: (v) => {
  103. return {
  104. data: superjson.parse(v.data),
  105. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  106. };
  107. },
  108. },
  109. 'IPageToShowRevisionWithMetaTransformer',
  110. );
  111. // GrowiContextualSubNavigation for NOT shared page
  112. type GrowiContextualSubNavigationProps = {
  113. isLinkSharingDisabled: boolean,
  114. }
  115. const GrowiContextualSubNavigation = (props: GrowiContextualSubNavigationProps): JSX.Element => {
  116. const { isLinkSharingDisabled } = props;
  117. const { data: currentPage } = useSWRxCurrentPage();
  118. return (
  119. <GrowiContextualSubNavigationSubstance currentPage={currentPage} isLinkSharingDisabled={isLinkSharingDisabled} />
  120. );
  121. };
  122. type Props = CommonProps & {
  123. pageWithMeta: IPageToShowRevisionWithMeta | null,
  124. // pageUser?: any,
  125. redirectFrom?: string;
  126. // shareLinkId?: string;
  127. isLatestRevision?: boolean,
  128. isIdenticalPathPage?: boolean,
  129. isForbidden: boolean,
  130. isNotFound: boolean,
  131. isNotCreatable: boolean,
  132. // isAbleToDeleteCompletely: boolean,
  133. templateTagData?: string[],
  134. templateBodyData?: string,
  135. isLocalAccountRegistrationEnabled: boolean,
  136. isSearchServiceConfigured: boolean,
  137. isSearchServiceReachable: boolean,
  138. isSearchScopeChildrenAsDefault: boolean,
  139. elasticsearchMaxBodyLengthToIndex: number,
  140. isEnabledMarp: boolean,
  141. sidebarConfig: ISidebarConfig,
  142. isSlackConfigured: boolean,
  143. // isMailerSetup: boolean,
  144. isAclEnabled: boolean,
  145. // hasSlackConfig: boolean,
  146. drawioUri: string | null,
  147. noCdn: string,
  148. // highlightJsStyle: string,
  149. isAllReplyShown: boolean,
  150. isContainerFluid: boolean,
  151. isUploadEnabled: boolean,
  152. isUploadAllFileAllowed: boolean,
  153. isEnabledStaleNotification: boolean,
  154. isEnabledAttachTitleHeader: boolean,
  155. // isEnabledLinebreaks: boolean,
  156. // isEnabledLinebreaksInComments: boolean,
  157. adminPreferredIndentSize: number,
  158. isIndentSizeForced: boolean,
  159. disableLinkSharing: boolean,
  160. skipSSR: boolean,
  161. ssrMaxRevisionBodyLength: number,
  162. yjsData: CurrentPageYjsData,
  163. rendererConfig: RendererConfig,
  164. };
  165. const Page: NextPageWithLayout<Props> = (props: Props) => {
  166. // register global EventEmitter
  167. if (isClient() && window.globalEmitter == null) {
  168. window.globalEmitter = new EventEmitter();
  169. }
  170. const router = useRouter();
  171. useCurrentUser(props.currentUser ?? null);
  172. // commons
  173. useCsrfToken(props.csrfToken);
  174. useGrowiCloudUri(props.growiCloudUri);
  175. // page
  176. useIsContainerFluid(props.isContainerFluid);
  177. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  178. useIsForbidden(props.isForbidden);
  179. useIsNotCreatable(props.isNotCreatable);
  180. useRedirectFrom(props.redirectFrom ?? null);
  181. useIsSharedUser(false); // this page cann't be routed for '/share'
  182. useIsIdenticalPath(props.isIdenticalPathPage ?? false);
  183. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  184. useIsSearchPage(false);
  185. useIsEnabledAttachTitleHeader(props.isEnabledAttachTitleHeader);
  186. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  187. useIsSearchServiceReachable(props.isSearchServiceReachable);
  188. useElasticsearchMaxBodyLengthToIndex(props.elasticsearchMaxBodyLengthToIndex);
  189. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  190. useIsSlackConfigured(props.isSlackConfigured);
  191. // useIsMailerSetup(props.isMailerSetup);
  192. useIsAclEnabled(props.isAclEnabled);
  193. // useHasSlackConfig(props.hasSlackConfig);
  194. // useNoCdn(props.noCdn);
  195. useDefaultIndentSize(props.adminPreferredIndentSize);
  196. useIsIndentSizeForced(props.isIndentSizeForced);
  197. useDisableLinkSharing(props.disableLinkSharing);
  198. useRendererConfig(props.rendererConfig);
  199. useIsEnabledMarp(props.rendererConfig.isEnabledMarp);
  200. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  201. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  202. useIsAllReplyShown(props.isAllReplyShown);
  203. useIsUploadAllFileAllowed(props.isUploadAllFileAllowed);
  204. useIsUploadEnabled(props.isUploadEnabled);
  205. useIsLocalAccountRegistrationEnabled(props.isLocalAccountRegistrationEnabled);
  206. const { pageWithMeta } = props;
  207. const pageId = pageWithMeta?.data._id;
  208. const revisionBody = pageWithMeta?.data.revision?.body;
  209. useCurrentPathname(props.currentPathname);
  210. const { data: currentPage } = useSWRxCurrentPage(pageWithMeta?.data ?? null); // store initial data
  211. const { trigger: mutateCurrentPage } = useSWRMUTxCurrentPage();
  212. const { trigger: mutateCurrentPageYjsDataFromApi } = useSWRMUTxCurrentPageYjsData();
  213. const { mutate: mutateEditingMarkdown } = useEditingMarkdown();
  214. const { data: currentPageId, mutate: mutateCurrentPageId } = useCurrentPageId();
  215. const { mutate: mutateIsNotFound } = useIsNotFound();
  216. const { mutate: mutateIsLatestRevision } = useIsLatestRevision();
  217. const { mutate: mutateRemoteRevisionId } = useRemoteRevisionId();
  218. const { mutate: mutateTemplateTagData } = useTemplateTagData();
  219. const { mutate: mutateTemplateBodyData } = useTemplateBodyData();
  220. const { mutate: mutateCurrentPageYjsData } = useCurrentPageYjsData();
  221. useSetupGlobalSocket();
  222. useSetupGlobalSocketForPage(pageId);
  223. // Store initial data (When revisionBody is not SSR)
  224. useEffect(() => {
  225. if (!props.skipSSR) {
  226. return;
  227. }
  228. if (currentPageId != null && !props.isNotFound) {
  229. const mutatePageData = async() => {
  230. const pageData = await mutateCurrentPage();
  231. mutateEditingMarkdown(pageData?.revision?.body);
  232. mutateCurrentPageYjsDataFromApi();
  233. };
  234. // If skipSSR is true, use the API to retrieve page data.
  235. // Because pageWIthMeta does not contain revision.body
  236. mutatePageData();
  237. }
  238. }, [currentPageId, mutateCurrentPage, mutateCurrentPageYjsDataFromApi, mutateEditingMarkdown, props.isNotFound, props.skipSSR]);
  239. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  240. useEffect(() => {
  241. const decodedURI = decodeURI(window.location.pathname);
  242. if (isClient() && decodedURI !== props.currentPathname) {
  243. const { search, hash } = window.location;
  244. router.replace(`${props.currentPathname}${search}${hash}`, undefined, { shallow: true });
  245. }
  246. }, [props.currentPathname, router]);
  247. // initialize mutateEditingMarkdown only once per page
  248. // need to include useCurrentPathname not useCurrentPagePath
  249. useEffect(() => {
  250. if (props.currentPathname != null) {
  251. mutateEditingMarkdown(revisionBody);
  252. }
  253. }, [mutateEditingMarkdown, revisionBody, props.currentPathname]);
  254. useEffect(() => {
  255. mutateRemoteRevisionId(pageWithMeta?.data.revision?._id);
  256. }, [mutateRemoteRevisionId, pageWithMeta?.data.revision?._id]);
  257. useEffect(() => {
  258. mutateCurrentPageId(pageId ?? null);
  259. }, [mutateCurrentPageId, pageId]);
  260. useEffect(() => {
  261. mutateIsNotFound(props.isNotFound);
  262. }, [mutateIsNotFound, props.isNotFound]);
  263. useEffect(() => {
  264. mutateIsLatestRevision(props.isLatestRevision);
  265. }, [mutateIsLatestRevision, props.isLatestRevision]);
  266. useEffect(() => {
  267. mutateTemplateTagData(props.templateTagData);
  268. }, [props.templateTagData, mutateTemplateTagData]);
  269. useEffect(() => {
  270. mutateTemplateBodyData(props.templateBodyData);
  271. }, [props.templateBodyData, mutateTemplateBodyData]);
  272. useEffect(() => {
  273. mutateCurrentPageYjsData(props.yjsData);
  274. }, [mutateCurrentPageYjsData, props.yjsData]);
  275. // If the data on the page changes without router.push, pageWithMeta remains old because getServerSideProps() is not executed
  276. // So preferentially take page data from useSWRxCurrentPage
  277. const pagePath = currentPage?.path ?? pageWithMeta?.data.path ?? props.currentPathname;
  278. const title = generateCustomTitleForPage(props, pagePath);
  279. return (
  280. <>
  281. <Head>
  282. <title>{title}</title>
  283. </Head>
  284. <div className="dynamic-layout-root justify-content-between">
  285. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  286. <PageView
  287. className="d-edit-none"
  288. pagePath={pagePath}
  289. initialPage={pageWithMeta?.data}
  290. rendererConfig={props.rendererConfig}
  291. />
  292. <EditablePageEffects />
  293. <DisplaySwitcher />
  294. <PageStatusAlert />
  295. </div>
  296. </>
  297. );
  298. };
  299. const BasicLayoutWithEditor = ({ children }: { children?: ReactNode }): JSX.Element => {
  300. const editorModeClassName = useEditorModeClassName();
  301. return <BasicLayout className={editorModeClassName}>{children}</BasicLayout>;
  302. };
  303. type LayoutProps = Props & {
  304. children?: ReactNode
  305. }
  306. const Layout = ({ children, ...props }: LayoutProps): JSX.Element => {
  307. // init sidebar config with UserUISettings and sidebarConfig
  308. useInitSidebarConfig(props.sidebarConfig, props.userUISettings);
  309. return <BasicLayoutWithEditor>{children}</BasicLayoutWithEditor>;
  310. };
  311. Page.getLayout = function getLayout(page: React.ReactElement<Props>) {
  312. return (
  313. <>
  314. <GrowiPluginsActivator />
  315. <DrawioViewerScript drawioUri={page.props.rendererConfig.drawioUri} />
  316. <Layout {...page.props}>
  317. {page}
  318. </Layout>
  319. <UnsavedAlertDialog />
  320. <DescendantsPageListModal />
  321. <DrawioModal />
  322. <HandsontableModal />
  323. <QuestionnaireModalManager />
  324. <TemplateModal />
  325. <LinkEditModal />
  326. <TagEditModal />
  327. <ConflictDiffModal />
  328. </>
  329. );
  330. };
  331. function getPageIdFromPathname(currentPathname: string): string | null {
  332. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  333. }
  334. class MultiplePagesHitsError extends ExtensibleCustomError {
  335. pagePath: string;
  336. constructor(pagePath: string) {
  337. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  338. this.pagePath = pagePath;
  339. }
  340. }
  341. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  342. const { model: mongooseModel } = await import('mongoose');
  343. const req: CrowiRequest = context.req as CrowiRequest;
  344. const { crowi } = req;
  345. const { revisionId } = req.query;
  346. const Page = crowi.model('Page') as PageModel;
  347. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  348. const { pageService, configManager } = crowi;
  349. let currentPathname = props.currentPathname;
  350. const pageId = getPageIdFromPathname(currentPathname);
  351. const isPermalink = _isPermalink(currentPathname);
  352. const { user } = req;
  353. if (!isPermalink) {
  354. // check redirects
  355. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  356. if (chains != null) {
  357. // overwrite currentPathname
  358. currentPathname = chains.end.toPath;
  359. props.currentPathname = currentPathname;
  360. // set redirectFrom
  361. props.redirectFrom = chains.start.fromPath;
  362. }
  363. // check whether the specified page path hits to multiple pages
  364. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  365. if (count > 1) {
  366. throw new MultiplePagesHitsError(currentPathname);
  367. }
  368. }
  369. const pageWithMeta: IPageToShowRevisionWithMeta | null = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  370. const page = pageWithMeta?.data as unknown as PageDocument;
  371. // add user to seen users
  372. if (page != null && user != null) {
  373. await page.seen(user);
  374. }
  375. // populate & check if the revision is latest
  376. if (page != null) {
  377. page.initLatestRevisionField(revisionId);
  378. props.isLatestRevision = page.isLatestRevision();
  379. const ssrMaxRevisionBodyLength = configManager.getConfig('crowi', 'app:ssrMaxRevisionBodyLength');
  380. props.skipSSR = await skipSSR(page, ssrMaxRevisionBodyLength);
  381. await page.populateDataToShowRevision(props.skipSSR); // shouldExcludeBody = skipSSR
  382. }
  383. props.pageWithMeta = pageWithMeta;
  384. }
  385. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  386. const req: CrowiRequest = context.req as CrowiRequest;
  387. const { crowi } = req;
  388. const Page = crowi.model('Page') as PageModel;
  389. const { currentPathname } = props;
  390. const pageId = getPageIdFromPathname(currentPathname);
  391. const isPermalink = _isPermalink(currentPathname);
  392. const page = props.pageWithMeta?.data;
  393. if (props.isIdenticalPathPage) {
  394. props.isNotCreatable = true;
  395. }
  396. else if (page == null) {
  397. props.isNotFound = true;
  398. props.isNotCreatable = !isCreatablePage(currentPathname);
  399. // check the page is forbidden or just does not exist.
  400. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  401. props.isForbidden = count > 0;
  402. }
  403. else {
  404. props.isNotFound = page.isEmpty;
  405. props.isNotCreatable = false;
  406. props.isForbidden = false;
  407. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  408. if (isPermalink && page.isEmpty) {
  409. props.currentPathname = page.path;
  410. }
  411. // /path/to/page ==> /62a88db47fed8b2d94f30000
  412. if (!isPermalink && !page.isEmpty) {
  413. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  414. if (!isToppage) {
  415. props.currentPathname = `/${page._id}`;
  416. }
  417. }
  418. if (!props.skipSSR) {
  419. props.yjsData = await crowi.pageService.getYjsData(page._id.toString());
  420. }
  421. }
  422. }
  423. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  424. // const req: CrowiRequest = context.req as CrowiRequest;
  425. // const { crowi } = req;
  426. // const UserModel = crowi.model('User');
  427. // if (isUserPage(props.currentPagePath)) {
  428. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  429. // if (user != null) {
  430. // props.pageUser = JSON.stringify(user.toObject());
  431. // }
  432. // }
  433. // }
  434. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  435. const req: CrowiRequest = context.req as CrowiRequest;
  436. const { crowi } = req;
  437. const {
  438. searchService, configManager, aclService,
  439. } = crowi;
  440. props.isSearchServiceConfigured = searchService.isConfigured;
  441. props.isSearchServiceReachable = searchService.isReachable;
  442. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  443. props.elasticsearchMaxBodyLengthToIndex = configManager.getConfig('crowi', 'app:elasticsearchMaxBodyLengthToIndex');
  444. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  445. // props.isMailerSetup = mailService.isMailerSetup;
  446. props.isAclEnabled = aclService.isAclEnabled();
  447. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  448. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  449. props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  450. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  451. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  452. props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  453. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  454. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  455. props.isUploadAllFileAllowed = crowi.fileUploadService.getFileUploadEnabled();
  456. props.isUploadEnabled = crowi.fileUploadService.getIsUploadable();
  457. props.isLocalAccountRegistrationEnabled = crowi.passportService.isLocalStrategySetup
  458. && configManager.getConfig('crowi', 'security:registrationMode') !== RegistrationMode.CLOSED;
  459. props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  460. props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  461. props.isEnabledAttachTitleHeader = configManager.getConfig('crowi', 'customize:isEnabledAttachTitleHeader');
  462. props.sidebarConfig = {
  463. isSidebarCollapsedMode: configManager.getConfig('crowi', 'customize:isSidebarCollapsedMode'),
  464. isSidebarClosedAtDockMode: configManager.getConfig('crowi', 'customize:isSidebarClosedAtDockMode'),
  465. };
  466. props.rendererConfig = {
  467. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  468. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  469. isEnabledMarp: configManager.getConfig('crowi', 'customize:isEnabledMarp'),
  470. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  471. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  472. drawioUri: configManager.getConfig('crowi', 'app:drawioUri'),
  473. plantumlUri: configManager.getConfig('crowi', 'app:plantumlUri'),
  474. // XSS Options
  475. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:rehypeSanitize:isEnabledPrevention'),
  476. sanitizeType: configManager.getConfig('markdown', 'markdown:rehypeSanitize:option'),
  477. customAttrWhitelist: JSON.parse(crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:attributes')),
  478. customTagWhitelist: crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:tagNames'),
  479. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  480. };
  481. props.ssrMaxRevisionBodyLength = configManager.getConfig('crowi', 'app:ssrMaxRevisionBodyLength');
  482. }
  483. /**
  484. * for Server Side Translations
  485. * @param context
  486. * @param props
  487. * @param namespacesRequired
  488. */
  489. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  490. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  491. props._nextI18Next = nextI18NextConfig._nextI18Next;
  492. }
  493. const getAction = (props: Props): SupportedActionType => {
  494. if (props.isNotCreatable) {
  495. return SupportedAction.ACTION_PAGE_NOT_CREATABLE;
  496. }
  497. if (props.isForbidden) {
  498. return SupportedAction.ACTION_PAGE_FORBIDDEN;
  499. }
  500. if (props.isNotFound) {
  501. return SupportedAction.ACTION_PAGE_NOT_FOUND;
  502. }
  503. if (pagePathUtils.isUsersHomepage(props.pageWithMeta?.data.path ?? '')) {
  504. return SupportedAction.ACTION_PAGE_USER_HOME_VIEW;
  505. }
  506. return SupportedAction.ACTION_PAGE_VIEW;
  507. };
  508. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  509. const req = context.req as CrowiRequest;
  510. const { user } = req;
  511. const result = await getServerSideCommonProps(context);
  512. // check for presence
  513. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  514. if (!('props' in result)) {
  515. throw new Error('invalid getSSP result');
  516. }
  517. const props: Props = result.props as Props;
  518. if (props.redirectDestination != null) {
  519. return {
  520. redirect: {
  521. permanent: false,
  522. destination: props.redirectDestination,
  523. },
  524. };
  525. }
  526. if (user != null) {
  527. props.currentUser = user.toObject();
  528. }
  529. try {
  530. await injectPageData(context, props);
  531. }
  532. catch (err) {
  533. if (err instanceof MultiplePagesHitsError) {
  534. props.isIdenticalPathPage = true;
  535. }
  536. else {
  537. throw err;
  538. }
  539. }
  540. await injectRoutingInformation(context, props);
  541. injectServerConfigurations(context, props);
  542. await injectNextI18NextConfigurations(context, props, ['translation']);
  543. addActivity(context, getAction(props));
  544. return {
  545. props,
  546. };
  547. };
  548. export default Page;